// pages/detail/detail.js
import config from "../../utils/config";

const app = getApp()
import _ from './../../utils/lodash.js';
import util from './../../utils/util.js';

const find = _.find;


function isNumericStart(str) {
    return /^\d/.test(str);
}

function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}

let EBOriginData = '';
let upgradeIndex = 1;
let per_package_size = 128
Page({

    /**
     * 页面的初始数据
     */
    data: {
        active: 1,
        deviceId: '',
        name: '',
        zcbh:'',
        address:'',
        type: '',
        connected: false,
        loading: false,
        serviceIds: [],
        serviceIdsCharIdsMap: [],
        selectServerChars: {},
        logs: [],
        all_concentrator_firmwares: [],
        latitude: '',
        longitude: '',
        editlatitude: 42.92736760935551,
        editlongitude: 89.19229343394916,
        dateIndex: util.formatDate(new Date()),
        collected_at: '',
        parameters: {},
        ble1Data:{}
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const that = this
        console.log(options);
        this.setData({
            deviceId: options.deviceId,
            name: options.name.split("-")[1],
            connected: options.connected === '1',
        }, function () {
            this.createBLEConnection()
            this.getDevice()
            // this.getBLEDeviceServices(this.data.deviceId)
        })
        wx.setNavigationBarTitle({
            title: options.type,
        })
        wx.onBLEConnectionStateChange(function (res) {
            // 该方法回调中可以用于处理连接意外断开等异常情况
            console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            that.writeLogs(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
            that.setData({
                connected: res.connected
            }, function () {
                if (res.connected) {
                    this.getBLEDeviceServices(this.data.deviceId)
                } else {
                    that.writeLogs('断开连接')
                }
            })
        })


    },
    getLocation: function () {
        const that = this;
        this.editmapCtx2 = wx.createMapContext('myMap2')
        console.log('getLocation')
        wx.chooseLocation({
            success: res => {
                console.log(res)
                this.setData({
                    editaddress: res.name,
                    editlatitude: res.latitude,
                    editlongitude: res.longitude,
                    editmarkers: [{
                        id: 1,
                        latitude: res.latitude,
                        longitude: res.longitude,
                        width: '30', // 标记点图标宽度
                        height: '60' // 标记点图标高度
                    }],
                })
                // if(that.editmapCtx2){
                //     that.editmapCtx2.moveToLocation()
                // }
            },
            fail: err => {
                console.log(err)
            }
        })
        /*wx.getLocation({
            type: 'wgs84',
            success (res) {
                console.log(res)
              const latitude = res.latitude
              const longitude = res.longitude
              const speed = res.speed
              const accuracy = res.accuracy
              that.setData({
                editlatitude:latitude,
                editlongitude:longitude,
                editmarkers: [{
                    id:accuracy,
                    longitude: longitude,
                    latitude: latitude,
                    width: '30', // 标记点图标宽度
					height: '50' // 标记点图标高度
                  }]
              })
              if(that.editmapCtx2){
                that.editmapCtx2.moveToLocation()
              }
            //   that.editmapCtx2.moveToLocation()

            }
           })*/
    },
    bindmarkertap: function () {
        wx.openLocation({
            latitude: Number(this.data.latitude), // 纬度，范围为-90~90，负数表示南纬
            longitude: Number(this.data.longitude), // 经度，范围为-180~180，负数表示西经
            scale: 14, // 缩放比例
        })
    },
    changeInput: function (e) {
        const that = this
        console.log('changeValue', e.currentTarget.dataset.item)
        console.log('e.detail.value', e.detail.value)
        this.setData({
            [e.currentTarget.dataset.item]: e.detail.value
        })
    },
    bindTimeChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            timeIndex: e.detail.value
        })
    },
    bindChangeDate: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            dateIndex: e.detail.value
        })
    },
    checkboxChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        const items = this.data.checkItems
        const values = e.detail.value
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            items[i].checked = false

            for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
                if (items[i].value === values[j]) {
                    items[i].checked = true
                    break
                }
            }
        }

        this.setData({
            checkItems: items
        })

    },
    valveCheckboxChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        const items = this.data.checkValveItems
        const values = e.detail.value
        for (let i = 0, lenI = items.length; i < lenI; ++i) {
            items[i].checked = false

            for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
                if (items[i].value === values[j]) {
                    items[i].checked = true
                    break
                }
            }
        }

        this.setData({
            checkValveItems: items
        })

    },
    clean: function (e) {

        this.setData({
            logs: []
        })
    },
    bindPickerChangePost: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            postIndex: e.detail.value
        })
    },
    bindPickerChangePostEvent: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            eventIndex: Number(e.detail.value),
            F0data: {}
        })
    },
    bindPickerChangePost2: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            postIndex2: e.detail.value
        })
    },
    bindPickerChangeValve: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            valveIndex: e.detail.value
        })
    },
    getName: function () {
        let n1 = this.data.name.substr(0, 2)
        let n2 = this.data.name.substr(2, 2)
        let n3 = this.data.name.substr(4, 2)
        let n4 = this.data.name.substr(6, 2)
        return `${n4} ${n3} ${n2} ${n1}`
    },
    getTime: function () {
        let date = util.formatTime(new Date())
        let b1 = date.substr(0, 2)
        let b2 = date.substr(2, 2)
        let b3 = date.substr(5, 2)
        let b4 = date.substr(8, 2)
        let b5 = date.substr(11, 2)
        let b6 = date.substr(14, 2)
        let b7 = date.substr(17, 2)
        return `${b7} ${b6} ${b5} ${b4} ${b3} ${b2} ${b1}`
    },
    writeBLECharacteristicValue(sendHex) {
        if (!this.data.connected) {
            util.toastError('请先连接设备');
            return false
        }
        if (!this.data.selectServerChars.deviceId) {
            util.toastError('请等待初始化或者重新连接')
            return false
        }
        var typedArray = new Uint8Array(sendHex.match(/[\dA-F]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        }))
        // console.log(typedArray)
        const that = this
        var writeValue = typedArray.buffer
        wx.writeBLECharacteristicValue({
            deviceId: this.data.selectServerChars.deviceId,
            serviceId: this.data.selectServerChars.serviceId,
            characteristicId: this.data.selectServerChars.writeCharUUID,
            value: writeValue,
            success(res) {
                // that.writeLogs("下发数据成功: " + sendHex, 'green');
                // console.log(sendHex.substr(12, 2))
                //68 0E 68 57 89 76 00 89 01 00 00
                // console.log(sendHex)
                util.toastError('操作下发成功')


            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("下发数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },
    recvBLECharacterNotice: function (deviceId, serviceId, charId) {
        //接收设置是否成功
        // this.writeLogs("注册Notify服务");
        var that = this;
        wx.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: charId,
            state: true, //启用Notify功能
            success: function (res) {
                wx.onBLECharacteristicValueChange(function (res) {
                    console.log(res);
                    that.writeLogs("收到Notify数据: " + util.addSpaceEveryTwoChars(util.ab2hex(res.value)));
                    let notifyData = util.ab2hex(res.value)
                    console.log('notifyData', notifyData)
                    const name=that.data.name
                    console.log(`${name.substr(8, 2)}${name.substr(6, 2)}${name.substr(4, 2)}${name.substr(2, 2)}${name.substr(0, 2)}`)
                    if (notifyData.substr(0, 14) === `6810${name.substr(8, 2)}${name.substr(6, 2)}${name.substr(4, 2)}${name.substr(2, 2)}${name.substr(0, 2)}`) {
                        console.log('指令1返回')
                        util.toastError('蓝牙获取数据成功')
                        that.setData({
                            ble1Data:{
                                instantaneous_flow:Number((Number(`${notifyData.substr(34,2)}${notifyData.substr(32,2)}${notifyData.substr(30,2)}${notifyData.substr(28,2)}`)/100).toFixed(2)),
                                cumulative_flow:Number((Number(`${notifyData.substr(44,2)}${notifyData.substr(42,2)}${notifyData.substr(40,2)}${notifyData.substr(38,2)}`)/100).toFixed(2))
                            }
                        })

                    }
                    if (notifyData.toUpperCase() === `680EF168AAAAAAAAAAAAAAF0409008006E16`) {
                        console.log('指令2返回')
                        util.toastError('触发上线成功')

                    }

                });
            },
            fail: function (res) {
                console.log(res);
                that.writeLogs("接收数据失败: " + res.errCode, 'red');
                util.bleErrCode(res.errCode);
            }
        })
    },

    writeLogs(text, color) {
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        let logs = this.data.logs;
        logs.unshift({
            color: color ? color : '#000',
            text: text,
            time: util.formatNumber(hours) + ':' + util.formatNumber(minutes) + ':' + util.formatNumber(seconds)
        })
        this.setData({
            logs
        })
    },
    createBLEConnection() {
        console.log('createBLEConnection')
        this.setData({
            loading: true,
        })
        wx.createBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                util.toastError('连接成功');
                this.writeLogs('连接成功')
                wx.setBLEMTU({
                    deviceId: this.data.deviceId,
                    mtu: 256,
                    success: (res) => {
                        console.log('设置MTU256成功')
                        this.writeLogs('设置MTU256成功')
                    },
                    fail: (res) => {
                        console.log('设置MTU失败')
                        console.log(res)
                    },
                })
                console.log("createBLEConnection success")
                this.setData({
                    connected: true,
                    loading: false,
                }, function () {
                    // this.getBLEDeviceServices(this.data.deviceId);
                })

            },
            fail: (res) => {
                util.bleErrCode(res.errCode);
                this.writeLogs('连接失败,' + util.bleErrCode(res.errCode))
                console.log('连接失败')
                console.log(res)
                if (res.errCode === -1) {
                    this.setData({
                        connected: true,
                        loading: false,
                    })
                } else {
                    this.setData({
                        loading: false,
                    })
                }

            }
        })

    },
    closeBLEConnection() {
        const that = this
        wx.closeBLEConnection({
            deviceId: this.data.deviceId,
            success: (res) => {
                console.log("closeBLEConnection success")
                util.toastError('断开连接成功');
                that.writeLogs('断开连接成功')
                that.setData({
                    connected: false
                })

            },
            fail: (res) => {
                that.writeLogs('断开连接失败')
                console.log('断开连接失败')
                util.bleErrCode(res.errCode);
                console.log(res)
            }
        })


    },
    clickTop(e) {
        const ds = e.currentTarget.dataset
        const item = ds.item
        this.setData({
            active: item
        })
    },
    getBLEDeviceServices(deviceId) {
        const that = this
        wx.getBLEDeviceServices({
            deviceId: this.data.deviceId,
            success: (res) => {
                console.log('所有服务', res.services)
                let serviceIds = [];
                for (let i = 0; i < res.services.length; i++) {

                    //安卓上，部分机型获取设备服务时会多出 00001800 和 00001801 UUID 的服务，这是系统行为，注意不要使用这两个服务。
                    if (res.services[i].uuid.indexOf('00001800') >= 0 || res.services[i].uuid.indexOf('00001801') >= 0
                        || res.services[i].uuid.indexOf('0000180A') >= 0) {
                        console.log(`res.services[i].uuid ${res.services[i].uuid} 是系统行为，不要使用`)
                    } else {
                        console.log('res.services[i].uuid', res.services[i].uuid)
                        serviceIds.push(res.services[i].uuid)

                    }

                }
                this.setData({
                    serviceIds: serviceIds
                }, function () {
                    for (let i = 0; i < this.data.serviceIds.length; i++) {
                        setTimeout(function () {
                            that.getBLEDeviceCharacteristics(deviceId, that.data.serviceIds[i])
                        }, 100)

                    }
                })
            }
        })
    },
    getBLEDeviceCharacteristics(deviceId, serviceId) {
        const that = this;
        wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId,
            success: (res) => {
                console.log('getBLEDeviceCharacteristics success', res.characteristics)

                let findWrite = find(res.characteristics, function (o) {
                    return o.properties.write
                })
                let findNotify = find(res.characteristics, function (o) {
                    return o.properties.notify
                })
                // let findWrite =res.characteristics[2]
                // let findNotify =res.characteristics[2]

                if (findWrite && findNotify) {

                    this.setData({
                        selectServerChars: {
                            deviceId: deviceId,
                            serviceId: serviceId,
                            writeCharUUID: findWrite.uuid,
                            notifyCharUUID: findNotify.uuid,
                        }
                    }, function () {

                        console.log('selectServerChars', this.data.selectServerChars)
                        this.recvBLECharacterNotice(deviceId, serviceId, this.data.selectServerChars.notifyCharUUID);
                        this.writeLogs(`发现服务${JSON.stringify(this.data.selectServerChars)}`, 'rgb(232,137,60)')
                        setTimeout(function () {
                            that.handle1()
                        }, 1000)
                    })

                }


            },
            fail(res) {
                console.log('serviceId 出错了', serviceId)
                console.error('getBLEDeviceCharacteristics', res)
                util.bleErrCode(res.errCode);
                that.writeLogs(util.bleErrCode(res.errCode), 'red')
            }
        })
        //监听蓝牙低功耗设备的特征值变化事件。必须先调用 wx.notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。
        wx.onBLECharacteristicValueChange((characteristic) => {
            console.log(characteristic.value)

        })
    },
    handle1: function () {
        const that = this
        let sendHex = '6810AAAAAAAAAAAAAA01031F9001D216BA'
        console.log('sendHex', sendHex)
        that.writeLogs(`下发数据：${sendHex}`, 'orange');
        that.writeBLECharacteristicValue(sendHex)
    },
    getDevice: function () {
        const that = this;
        const name = this.data.name
        wx.request({
            url: `${config.prefix}/hydrants`,
            header: {
                Authorization: `Bearer ${app.globalData.userInfo.token}`
            },
            method: 'GET',
            data: {
                number: name
            },
            success: function (res) {
                if (res.statusCode === 200) {
                    console.log('获取成功');
                    if (res.data.data.length === 1) {
                        that.setData({
                            zcbh:res.data.data[0].name,
                            address:res.data.data[0].address,
                            latitude:res.data.data[0].latitude,
                            longitude:res.data.data[0].longitude,
                            hydrant_id:res.data.data[0].id,
                            elevation:res.data.data[0].elevation,
                            renderMeterStatus:(res.data.data[0].latest_data.rtu&&res.data.data[0].latest_data.rtu.parameters)?util.renderMeterStatus(res.data.data[0].latest_data.rtu.parameters.meter_status):[],
                            parameters: res.data.data[0].latest_data.rtu.collected_at ? res.data.data[0].latest_data.rtu.parameters : {},
                            collected_at: res.data.data[0].latest_data.rtu.collected_at
                        })
                    } else {
                        console.log('系统中没有该设备')
                        wx.showToast({
                            title: '系统中没有该设备',
                            icon: 'none'
                        })
                        // util.toastError(`请先在系统中添加集中器${number}`)
                    }
                } else {
                    util.converErrorCodeToMsg(res)
                }

            }
        })
    },
    handleTest: function () {
        if (!this.data.connected) {
            util.toastError('巡检前请先连接设备蓝牙')
            return false
        }
        if (!('instantaneous_flow' in this.data.ble1Data)) {
            util.toastError('巡检前请先获取流量')
            return false
        }
        const that = this
        wx.showModal({
            title: '请输入巡检备注',
            editable: true,
            content: '',
            success(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    wx.request({
                        url: `${config.prefix}/hydrant_inspection_records`,
                        header: {
                            Authorization: `Bearer ${app.globalData.userInfo.token}`
                        },
                        method: 'POST',
                        data: {
                            remark: res.content,
                            latitude:that.data.latitude,
                            longitude:that.data.longitude,
                            hydrant_id:that.data.hydrant_id,
                            elevation:that.data.elevation,
                            parameters: that.data.ble1Data
                        },

                        success: function (res) {
                            console.log('get res', res)
                            if (res.statusCode === 200) {
                                util.toastError('巡检信息上传成功')


                            }else {
                                util.converErrorCodeToMsg(res)
                            }
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    handle2: function () {
        const that = this
        let sendHex = '680EF168AAAAAAAAAAAAAA7040900800EE16'
        console.log('sendHex', sendHex)
        that.writeLogs(`下发数据：${sendHex}`, 'orange');
        that.writeBLECharacteristicValue(sendHex)
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log('onHIde')
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('item onUnload')
        if (this.data.connected) {
            this.closeBLEConnection()
        }

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    // onPullDownRefresh() {
    //
    // },

    /**
     * 页面上拉触底事件的处理函数
     */
    // onReachBottom() {
    //
    // },

    /**
     * 用户点击右上角分享
     */
    // onShareAppMessage() {

    // }
})
